<script setup lang="ts">
import {onMounted, ref, onBeforeUnmount, getCurrentInstance} from "vue";
import {getProductAll} from "@/api/productApi.ts";

const {proxy} = getCurrentInstance();

const products = ref([]);
const fetchProductData = () => {
  getProductAll().then(res => {
    products.value = res.data;
  })
}

const intervalId = ref(0);
const startUpdating = () => {
  intervalId.value = setInterval(() => {
    fetchProductData();
  }, 3000);
}

onMounted(() => {
  fetchProductData();
  startUpdating();
});

// 在组件卸载之前清除定时器
onBeforeUnmount(() => {
  if (intervalId.value) {
    clearInterval(intervalId.value);
  }
});

</script>

<template>
  <div class="product">

    <van-grid :column-num="2" :gutter="5" :border="false">
      <van-grid-item v-for="item in products">
        <router-link :to="{name:'productDetail',params:{id:item.id}}" :class="['product-item',item.class]">
          <div class="content-item-left">
            <van-image width="50px" height="50px" :src="proxy.$baseURL + item.img_url"/>
          </div>

          <div class="product-item-right">
            <span style="color: #000000">{{ item.product_name }}</span>
            <span style="color: #000000">{{ item.sale }}</span>
            <span>{{ item.priceb }}%</span>
          </div>
        </router-link>
      </van-grid-item>
    </van-grid>
  </div>
</template>

<style scoped lang="less">
@import "../../less/product.less";
</style>